# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pandas as pd
import pymongo

class LagouPipeline(object):
    def process_item(self, item, spider):
        df = pd.DataFrame(dict(item))
        df.to_csv('LagouCityPage1.csv', encoding='gb18030', index=False)
        return item

class PositonPipeline(object):
    def __init__(self, mongo_uri, mongo_db,mongo_tb):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db
        self.mongo_tb = mongo_tb

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items'),
            mongo_tb=crawler.settings.get('MONGO_TABLE')
        )

    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def close_spider(self, spider):
        self.client.close()

    def process_item(self, item, spider):
        #name = item.__class__.__name__
        #self.db[name].insert_one(dict(item))
        self.db[self.mongo_tb].insert_one(dict(item))
        #self.db[name].update({'id': item['id']}, {'$set': item}, True)
        return item
